package com.hunantv.mglive.ui.discovery.publisher.pic;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.hunantv.mglive.utils.Toast;
import android.widget.ToggleButton;

import com.bumptech.glide.Glide;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BaseActivity;
import com.hunantv.mglive.common.Constant;
import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.utils.L;

import java.util.ArrayList;


interface OnPageClickListener {
    public void onPageClickListener(View view, int position);
};

public class PicPreviewActivity extends BaseActivity implements OnClickListener, OnPageClickListener,
        ViewPager.OnPageChangeListener, OnCheckedChangeListener {

    private ViewPager mPreViewPager;
    private PreViewAdapter mPreViewAdapter;
    private TextView mTitle;
    private RelativeLayout mTopBar;
    private View mBottomBar;
    private Button mBtnBack;
    private ToggleButton mPictureCheckBtn;
    private View mSelectCompelete;
    private TextView mSelectNumTips;

    private ArrayList<String> mPicList;
    private ArrayList<String> mPicSelectList;//todo: use hashset instead of ArrayList.. used by mode 1.
    private int mPosition;
    private boolean mShowPictureFullScreen = false;
    private int mMaxSelectCount = PublisherConstants.MAX_SELECT_PIC_COUNT;

    public static final int MODE_PREVIEW_AND_DELETE = 0;
    public static final int MODE_SELECT_AND_PREVIEW = 1;
    public static final int MODE_PREVIEW_ONLY = 2;
    private int mCurrentMode = MODE_PREVIEW_AND_DELETE;//0 -- can delete preview item(default). 1 --- only selected or unselect preview item not delete.
    private boolean mSelectStateChanged = false;

    private boolean mCanDownload = false;//下载图片
    private boolean mInDownload = false;
    private int mType = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.publisher_preview_photo);

        if (initData() == false)
            return;
        initUI();
    }

    private boolean initData() {
        Intent intent = getIntent();
        mPicList = intent.getStringArrayListExtra("piclists");
        if (mPicList == null)
            return false;
        mType = intent.getIntExtra("type", 0);
        mPosition = intent.getIntExtra("position", 0);
        mCurrentMode = intent.getIntExtra("currentMode", MODE_PREVIEW_AND_DELETE);
        mMaxSelectCount = intent.getIntExtra("maxSelectCount", PublisherConstants.MAX_SELECT_PIC_COUNT);
        mCanDownload = intent.getBooleanExtra("downloadPic", false);

        if (mCurrentMode == MODE_SELECT_AND_PREVIEW) {
            mPicSelectList = intent.getStringArrayListExtra("picselectlists");
            if (mPicSelectList == null) {
                mPicSelectList = new ArrayList<String>();
            }
        }

        return true;
    }

    private void initUI() {

        mTitle = (TextView) findViewById(R.id.title);
        UpdateTitle();

        mTopBar = (RelativeLayout) findViewById(R.id.top_bar);
        mBottomBar = findViewById(R.id.bottom_bar);
        if (1 == mType) {
            mBottomBar.setVisibility(View.GONE);
        }
        mBtnBack = (Button) findViewById(R.id.back_photo_list_btn);
        mBtnBack.setOnClickListener(this);

        if (mCanDownload) {
            Button btnSave = (Button) findViewById(R.id.btn_save);
            btnSave.setOnClickListener(this);
            btnSave.setVisibility(View.VISIBLE);
        }

        Button btnDelete = (Button) findViewById(R.id.btn_delete);
        if (1 == mType) {
            btnDelete.setVisibility(View.GONE);
        }
        btnDelete.setOnClickListener(this);
        if (mCurrentMode == MODE_PREVIEW_ONLY)
            btnDelete.setVisibility(View.INVISIBLE);

        mPictureCheckBtn = (ToggleButton) findViewById(R.id.photo_picture_check);
        mPictureCheckBtn.setOnCheckedChangeListener(this);
        if (mCurrentMode == MODE_SELECT_AND_PREVIEW) {
            btnDelete.setVisibility(View.INVISIBLE);
            mPictureCheckBtn.setVisibility(View.VISIBLE);
            if (1 != mType) {
                mBottomBar.setVisibility(View.VISIBLE);
            }
            mSelectCompelete = findViewById(R.id.btn_compelete);
            mSelectCompelete.setOnClickListener(this);
            mSelectNumTips = (TextView) findViewById(R.id.selectnum_tips);
            if (mPicList.size() > 0) {
                mSelectNumTips.setVisibility(View.VISIBLE);
                mSelectNumTips.setText(String.format("%d", getSelectedCount()));
            }

            if (mPosition == 0) {
                boolean bselected = mPicSelectList.contains(mPicList.get(mPosition));
                mPictureCheckBtn.setOnCheckedChangeListener(null);//only set check state...
                mPictureCheckBtn.setChecked(bselected);
                mPictureCheckBtn.setOnCheckedChangeListener(this);
            }

        }


        mPreViewPager = (ViewPager) findViewById(R.id.preview_viewpager);
        mPreViewPager.setPageMargin(25);
        mPreViewAdapter = new PreViewAdapter(this);
        mPreViewPager.setAdapter(mPreViewAdapter);
        mPreViewAdapter.setOnPageClickListener(this);
        mPreViewPager.setOnPageChangeListener(this);
        mPreViewPager.setCurrentItem(mPosition, false);
    }

    //update the title count
    private void UpdateTitle() {
        int pos = mPosition + 1;
        int count = mPicList.size();
        if (count == 0)
            pos = 0;
        String strText = (pos) + "/" + count;
        if (mTitle != null) {
            mTitle.setText(strText);
        }
    }

    private void UpdateFloatBarState() {
        mShowPictureFullScreen = !mShowPictureFullScreen;

        Animation transAnimation = null;
        float yStartPos, yEndPos;
        if (!mShowPictureFullScreen) {
            mTopBar.setVisibility(View.VISIBLE);
            yStartPos = -1.0f;
            yEndPos = 0.0f;
        } else {
            mTopBar.setVisibility(View.INVISIBLE);
            yStartPos = 0.0f;
            yEndPos = -1.0f;

        }

        transAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, // fromXType
                0.0f, // fromXValue
                Animation.RELATIVE_TO_SELF, // toXType
                0.0f, // toXValue
                Animation.RELATIVE_TO_SELF, // fromYType
                yStartPos, // fromYValue
                Animation.RELATIVE_TO_SELF, // toYType
                yEndPos);

        transAnimation.setDuration(200);
        mTopBar.startAnimation(transAnimation);

        if (mCurrentMode == MODE_SELECT_AND_PREVIEW) {
            if (!mShowPictureFullScreen) {
                mBottomBar.setVisibility(View.VISIBLE);
                yStartPos = 1.0f;
                yEndPos = 0.0f;
            } else {
                mBottomBar.setVisibility(View.INVISIBLE);
                yStartPos = 0.0f;
                yEndPos = 1.0f;
            }

            transAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, // fromXType
                    0.0f, // fromXValue
                    Animation.RELATIVE_TO_SELF, // toXType
                    0.0f, // toXValue
                    Animation.RELATIVE_TO_SELF, // fromYType
                    yStartPos, // fromYValue
                    Animation.RELATIVE_TO_SELF, // toYType
                    yEndPos);

            transAnimation.setDuration(200);
            mBottomBar.startAnimation(transAnimation);
        }
    }

    private int getSelectedCount() {
        if (mCurrentMode == MODE_SELECT_AND_PREVIEW) {
            if (mPicSelectList == null)
                return 0;
            return mPicSelectList.size();
        }
        return 0;
    }

    @Override
    public void onPageClickListener(View view, int position) {
        UpdateFloatBarState();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {


    }

    @Override
    public void onPageSelected(int position) {

        mPosition = position;//selected item...
        UpdateTitle();
        if (mCurrentMode == MODE_SELECT_AND_PREVIEW) {
            boolean bselected = mPicSelectList.contains(mPicList.get(position));
            mPictureCheckBtn.setOnCheckedChangeListener(null);//only set check state...
            mPictureCheckBtn.setChecked(bselected);
            mPictureCheckBtn.setOnCheckedChangeListener(this);
            mSelectNumTips.setText(String.format("%d", getSelectedCount()));
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    @Override
    public void onClick(View v) {
            if(v.getId() == R.id.back_photo_list_btn){
                OnPreViewCompelete(false);
            }else if(v.getId() == R.id.btn_delete){
                if (mCurrentMode == MODE_PREVIEW_AND_DELETE) {
                    mPicList.remove(mPosition);
                    UpdateTitle();
                    mSelectStateChanged = true;
                    if (mPicList.size() < 1) {
                        OnPreViewCompelete(false);
                    } else {
                        mPreViewAdapter.notifyDataSetChanged();
                    }
                }
            }else if(v.getId() == R.id.btn_compelete){
                OnPreViewCompelete(true);
            }else if(v.getId() == R.id.btn_save){
                if (mPicList.get(mPosition) != null && !mInDownload) {
                    //WupCommandExecutor.getInstance().addTask(downLoadImage(mPicList.get(mPosition)));
                }
            }

    }

//	private ImageDownloadRequest downLoadImage(String imgeUrl) {
//		mInDownload = true;
//		ImageDownloadRequest imageDownloadRequest = new ImageDownloadRequest(imgeUrl, new Response.Listener<String>() {
//			public void onResponse(String imageLocalPath) {
//				PicPreviewActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(imageLocalPath))));
//				Toaster.show(PicPreviewActivity.this, "图片已经保存到"+imageLocalPath, Toaster.SHORT);
//				MttLog.d("download", "download path " + imageLocalPath);
//				mInDownload = false;
//			}
//		}, new Response.ErrorListener() {
//			@Override
//			public void onErrorResponse(VolleyError error) {
//				Toaster.show(PicPreviewActivity.this, "保存图片失败: " + error.getMessage(), Toaster.SHORT);
//				mInDownload = false;
//			}
//
//		});
//		return imageDownloadRequest;
//	}


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // TODO Auto-generated method stub
        if (mCurrentMode == MODE_SELECT_AND_PREVIEW) {

            if (mMaxSelectCount == 1) {
                mPicSelectList.clear();
            } else if (mPicSelectList.size() >= mMaxSelectCount && isChecked) {
                mPictureCheckBtn.setOnCheckedChangeListener(null);//only set check state...
                mPictureCheckBtn.setChecked(false);
                mPictureCheckBtn.setOnCheckedChangeListener(this);
                Toast toast = Toast.makeText(this, "已经达到最大可选择的图片数量....", Toast.LENGTH_SHORT);
                toast.show();
                return;
            }

            if (isChecked) {
                if (!mPicSelectList.contains(mPicList.get(mPosition)))
                    mPicSelectList.add(mPicList.get(mPosition));
            } else {
                if (mPicSelectList.contains(mPicList.get(mPosition)))
                    mPicSelectList.remove(mPicList.get(mPosition));
            }
            mSelectStateChanged = true;
            mSelectNumTips.setText(String.format("%d", getSelectedCount()));
        }
    }


    @Override
    public void onBackPressed() {
        OnPreViewCompelete(false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPreViewAdapter.setOnPageClickListener(null);
        mPreViewPager.setOnPageChangeListener(null);
    }

    public void OnPreViewCompelete(boolean saveState) {

        Intent intent = new Intent();
        boolean selectStateChanged = false;
        if (mCurrentMode == MODE_PREVIEW_AND_DELETE)
            selectStateChanged = mSelectStateChanged;
        else if (mCurrentMode == MODE_SELECT_AND_PREVIEW)
            selectStateChanged = mSelectStateChanged & saveState;
        intent.putExtra("selectStateChanged", selectStateChanged);

        if (mCurrentMode == MODE_PREVIEW_AND_DELETE) {// can delete one item..
            intent.putStringArrayListExtra("piclists", mPicList);
            PicChooserResult.getInstance().resetResult(mPicList);
        } else if (selectStateChanged) {

            if (mCurrentMode == MODE_SELECT_AND_PREVIEW) {// select mode..
                intent.putStringArrayListExtra("piclists", mPicSelectList);
                PicChooserResult.getInstance().resetResult(mPicSelectList);
            }

            setResult(RESULT_OK, intent);// to PicChooserUI onActivityResult....

        }

        finish();
    }

    private class PreViewAdapter extends PagerAdapter {
        private Context mContext;
        private OnPageClickListener mOnPageClickListener = null;

        public PreViewAdapter(Context c) {
            mContext = c;
        }

        public void setOnPageClickListener(OnPageClickListener OnPageClickListener) {
            mOnPageClickListener = OnPageClickListener;
        }


        @Override
        public int getCount() {
            if (mPicList != null)
                return mPicList.size();
            return 0;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0 == arg1;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            L.d("picpreview", "instantiateItem position:" + position);
            View group = (View) LayoutInflater.from(MaxApplication.getApp().getAppContext()).inflate(R.layout.picture_preview_viewpager_pageitem, null);
            ImageView imgView = (ImageView) group.findViewById(R.id.imageView);

            String imgUrl = mPicList.get(position);
            if (imgUrl.startsWith("/")) {// 发送图片时，显示本地图片
                imgView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                //ImageUtils.setLocalImageToNetworkImageView(imgView, imgUrl);
                Glide.with(mContext).load(imgUrl).fitCenter().into(imgView);
            } else {
                imgView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                Glide.with(mContext).load(imgUrl).fitCenter().into(imgView);
                //imgView.setImageUrl(imgUrl, ImageCacheManager.getInstance().getImageLoader());
            }

            imgView.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    if (mOnPageClickListener != null) {
                        mOnPageClickListener.onPageClickListener(v, mPreViewPager.getCurrentItem());
                    }
                }
            });

            container.addView(group);
            return group;
            //		return null;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            L.d("picpreview", "destroyItem position:" + position);
            container.removeView((View) object);
        }

        //http://stackoverflow.com/questions/7369978/how-to-force-viewpager-to-re-instantiate-its-items
        //reinstaniate all items..when delete one item by notifyDataSetChanged..
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

    }


}
